package com.appliance.chamliga;

import java.io.IOException;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class WallpaperActivity extends RootActivity {

	private Gallery gallery;
	private ImageView imgView;

	private Integer[] Imgid = { R.drawable.bg, R.drawable.icon, R.drawable.list };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo);

		imgView = (ImageView) findViewById(R.id.ImageView01);

		if (currentImageIndex == -1) {
			imgView.setImageResource(Imgid[0]);
			currentImageResId = Imgid[0];
		} else {
			imgView.setImageResource(Imgid[currentImageIndex]);
			// currentImageResId = Imgid[currentImageIndex];
		}

		gallery = (Gallery) findViewById(R.id.examplegallery);
		gallery.setAdapter(new AddImgAdp(this));

		gallery.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("rawtypes")
			public void onItemClick(AdapterView parent, View v, int position, long id) {
				imgView.setImageResource(Imgid[position]);
				currentImageResId = Imgid[position];
				currentImageIndex = position;
			}
		});

		Button btn = (Button) findViewById(R.id.button1);
		btn.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Bitmap bitmap = BitmapFactory.decodeStream(getResources().openRawResource(currentImageResId));

				try {
					getApplicationContext().setWallpaper(bitmap);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

	public class AddImgAdp extends BaseAdapter {
		int GalItemBg;
		private Context cont;

		public AddImgAdp(Context c) {
			cont = c;
			TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
			GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
			typArray.recycle();
		}

		public int getCount() {
			return Imgid.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			ImageView imgView = new ImageView(cont);
			imgView.setImageResource(Imgid[position]);
			imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
			imgView.setScaleType(ImageView.ScaleType.FIT_XY);
			imgView.setBackgroundResource(GalItemBg);

			return imgView;
		}
	}

}